//
//  MeInformationEditVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2018/1/9.
//  Copyright © 2018年 beisheng. All rights reserved.
//

#import "MeInformationEditVC.h"
#import "BaseInfoIconCell.h"
#import "BaseInfoEditTextCell.h"
#import "EditMyInforModel.h"
#import "KeepCallBottomView.h"
#import <ZLPhotoBrowser/ZLPhotoActionSheet.h>

#import "ModifyPasswordVC.h"
@interface MeInformationEditVC ()
@property (nonatomic, strong) KeepCallBottomView *footerView;
@property (nonatomic, strong) NSMutableArray<PHAsset *> *lastSelectAssets;
@property (nonatomic, strong) NSMutableArray<UIImage *> *selectImages;
/** <#note#> */
@property (nonatomic, strong) EditMyInforModel *dataModel;

@end

@implementation MeInformationEditVC

- (EditMyInforModel *)dataModel{
    if (!_dataModel) {
        _dataModel = [[EditMyInforModel alloc]init];
        
        if (myViewModel.user.nick_name) {
            
            _dataModel.nickName = myViewModel.user.nick_name;

        }
        
        
        UIImage *image0 = [[[SDWebImageManager sharedManager] imageCache] imageFromDiskCacheForKey:myViewModel.user.user_headimg];
        
        if (image0) {
            _dataModel.selectImage = image0;
        }
        
        
    }
    
    
    return _dataModel;
}


- (KeepCallBottomView *)footerView{
    
    if (!_footerView) {
        
        KeepCallBottomView *temp = (KeepCallBottomView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([KeepCallBottomView class]) owner:nil options:nil].firstObject;
        
        [temp.topBtn setTitle:@"保 存" forState:UIControlStateNormal];
        [temp.topBtn setTitle:@"保 存" forState:UIControlStateHighlighted];
        
        [temp.topBtn addTarget:self action:@selector(saveInfomation) forControlEvents:UIControlEventTouchUpInside];
        
        _footerView = temp;
        
        [self.view addSubview:temp];
        
    }
    
    return _footerView;
}


- (void)saveInfomation{
    
    [self.view endEditing:YES];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    parameters[@"uid"] = [UserViewModel shareUserViewModel].user.uid;
  
    
 
    
    
    if (self.dataModel.nickName == nil) {
        
        [SVProgressHUD showInfoWithStatus:@"请填写用户昵称"];
        
        return;
    }
    
    parameters[@"nickname"] = self.dataModel.nickName;
    
    
    
    
    
    if (self.dataModel.selectImage == nil) {
        
        [SVProgressHUD showInfoWithStatus:@"请选择用户头像"];
        
        return;
    }
    
    

    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    
    //    manger.responseSerializer  = [AFHTTPResponseSerializer serializer];
    
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/plain", @"text/javascript",@"text/html" ,nil];
    
    NSString *url = @"http://feidu.baonongkang.cn/index.php/api/Member/updateMember";
    
    [SVProgressHUD showWithStatus:@"正在上传头像..."];

    
    MJWeakSelf
    [manger POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
      
        
                NSData * data = UIImageJPEGRepresentation([weakSelf.dataModel.selectImage getScaledImage], 1.0);
                NSString *name = @"nickNameImage";
                [formData appendPartWithFileData:data
                                            name:name
                                        fileName:[NSString stringWithFormat:@"%@.png",name]
                                        mimeType:@"application/octet-stream"];
                
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
              [SVProgressHUD showSuccessWithStatus:@"修改成功!"];
        
        //        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        //        NSLog(@"完成 %@", result);
        NSLog(@"%@",responseObject);

        myViewModel.user.nick_name = responseObject[@"data"][@"nick_name"];

        myViewModel.user.user_headimg = responseObject[@"data"][@"user_headimg"];
        
        myViewModel.user.user_tel = responseObject[@"data"][@"user_tel"];
        
        [myViewModel.user saveUserInfo];
        
        [weakSelf saveUserImage];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"userDidLoginOrInfoChange" object:nil];
        
//        [SVProgressHUD showSuccessWithStatus:responseObject[@"data"]];

        [weakSelf performSelector:@selector(back) withObject:nil afterDelay:2.0];
//
        

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [SVProgressHUD showErrorWithStatus:error.domain];
        
    }];
    
    
    
}


- (void)saveUserImage{
    
    
    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:myViewModel.user.user_headimg] options:kNilOptions progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        
        
        NSLog(@"22222222222");
        
    }];
    
    
}

- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"修改个人资料";
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([BaseInfoIconCell class]) bundle:nil] forCellReuseIdentifier:[BaseInfoIconCell identifierStr]];

    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([BaseInfoEditTextCell class]) bundle:nil] forCellReuseIdentifier:[BaseInfoEditTextCell identifierStr]];
    
    
    self.plainTableView.tableFooterView = self.footerView;


    // Do any additional setup after loading the view.
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    

   return 5;

    
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        BaseInfoIconCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[BaseInfoIconCell identifierStr]];
        
        tableCell.model = self.dataModel;
        
        
        return tableCell;
        
    } else if (indexPath.row == 4){
        
        
        return [[UITableViewCell alloc]init];

        
        
    }else{
        
        BaseInfoEditTextCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[BaseInfoEditTextCell identifierStr]];
        
        tableCell.index = indexPath;
        
        tableCell.model = self.dataModel;

        
        return tableCell;
    }
    
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row == 0) {
        return 90;
    } else if (indexPath.row == 4){
        return 0;
    }else{
        
        return 46;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    
    
    if (indexPath.row == 0) {
        [self selectImage];
    }
    
    if (indexPath.row == 1) {
        
        UIAlertController *contr = [UIAlertController alertControllerWithTitle:nil message:@"用户名不支持修改哟!" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        
        
        
        [contr addAction:action1];
        
        [self presentViewController:contr animated:YES completion:nil];
        
    }
    
    
    
    if (indexPath.row == 3) {
        
        ModifyPasswordVC *tempVC = [[ModifyPasswordVC alloc]init];
        
        [self.navigationController pushViewController:tempVC animated:YES];
    }
  
    
    
    
}


- (void)selectImage{
    
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    
    
    actionSheet.sender = self;
    
    actionSheet.navBarColor = themeColor;
    

    
    actionSheet.sortAscending = YES;
    actionSheet.allowSelectImage = YES;
    actionSheet.allowSelectGif = NO;
    actionSheet.allowSelectVideo = NO;
    actionSheet.allowSelectLivePhoto = NO;
    actionSheet.allowForceTouch = NO;
    actionSheet.allowEditImage = YES;
    actionSheet.allowTakePhotoInLibrary = YES;
    actionSheet.showSelectedMask = YES;
    actionSheet.editAfterSelectThumbnailImage = YES;
    actionSheet.clipRatios = @[GetClipRatio(1,1),GetClipRatio(4,3),GetClipRatio(3,2),GetClipRatio(16,9)];
    
    //设置照片最大选择数
    actionSheet.maxSelectCount = 1;
    
    actionSheet.arrSelectedAssets = self.lastSelectAssets;
    
    
    MJWeakSelf;
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        
        weakSelf.lastSelectAssets = [NSMutableArray arrayWithArray:assets];
        
        weakSelf.selectImages = [NSMutableArray arrayWithArray:images];
        
        weakSelf.dataModel.selectImage = self.selectImages.firstObject;
        
        [weakSelf.plainTableView reloadData];
        

    }];
    
    //调用相册
    [actionSheet showPhotoLibrary];
    
 
    
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [self.view endEditing:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
